<template>
  <div :style="bigScreenStyle" v-loading="loading">
    <template v-if="widgets.length">
      <widget-view
        v-for="(widgetItem, index) in widgets"
        :key="index"
        :index="index"
        :widgetData="widgetItem"
        :tenantId="tenantId"
        :isShare="isShare"
      />
    </template>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, CSSProperties } from 'vue'
import widgetView from './widgetView.vue'
import _ from 'lodash'
import { BigscreenApi } from '@/api/vmiot/bigscreen'
import { useMqttStore } from '@/store/modules/mqttStore'

const route = useRoute()
const id = ref<number>(Number(route.query.id))
const dashboard = ref<any>({})
const dashboardSet = ref<any>({})
const widgets = ref<any[]>([])
const tenantId = ref()

const bigScreenStyle = ref<CSSProperties>({})
const loading = ref(true)

// 是否是分享页面
const isShare = computed(() => route.path === '/bigscreen/share')

/**
 * 大屏处理数据
 * @param data
 */
const resolveScreenData = (data) => {
  dashboard.value = data
  dashboardSet.value = data.options.setup
  widgets.value = data.widgets

  bigScreenStyle.value = {
    width: `${dashboardSet.value.width}px`,
    height: `${dashboardSet.value.height}px`,
    backgroundColor: dashboardSet.value.backgroundColor,
    backgroundImage: 'url(' + dashboardSet.value.backgroundImage + ')',
    'background-position': '0% 0%',
    'background-size': '100% 100%',
    'background-repeat': 'initial',
    'background-attachment': 'initial',
    'background-clip': 'initial',
    'transform-origin': '0 0'
  }

  setScale()
}

const getData = async () => {
  let res: any
  if (isShare.value) {
    if (!id.value) {
      ElMessage.error('分享链接有误，请核查！')
      return
    }
    res = await BigscreenApi.getBigscreenByShare(id.value)
  } else {
    res = await BigscreenApi.getBigscreen(id.value)
  }
  loading.value = false
  tenantId.value = res.tenantId
  const dashboardData = JSON.parse(res.content)

  resolveScreenData(dashboardData)
}

const getScale = () => {
  let width = dashboardSet.value.width
  let height = dashboardSet.value.height
  return {
    scalex: window.innerWidth / width,
    scaley: window.innerHeight / height
  }
}

const setScale = () => {
  const scale = getScale()
  bigScreenStyle.value.transform = 'scale(' + scale.scalex + ',' + scale.scaley + ')'
}

const debouncedSetScale = _.debounce(setScale, 200)

onMounted(async () => {
  getData()
  // 启动 MQTT 连接
  const mqttStore = useMqttStore()
  mqttStore.connect()
  window.addEventListener('resize', debouncedSetScale)
})

onUnmounted(() => {
  window.removeEventListener('resize', debouncedSetScale)
})
</script>
<style lang="scss" scoped></style>
